package com.wufeng.service.oss;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

@Service
public class AliyunOssService {

    private final OSS ossClient;
    private final String ossBucket;
    private final String ossEndpoint;  // 如果还没有，请添加这一行

    @Autowired
    public AliyunOssService(OSS ossClient, @Value("${aliyun.oss.bucket}") String ossBucket, @Value("${aliyun.oss.endpoint}") String ossEndpoint) {
        this.ossClient = ossClient;
        this.ossBucket = ossBucket;
        this.ossEndpoint = ossEndpoint;
    }

    // 这个方法处理文件上传
    public String handleFileUpload(MultipartFile file, String uploadDir) throws IOException {
        // 生成上传到 OSS 的文件名，保存到指定目录下
        String originalFilename = file.getOriginalFilename();

        String fileName = + System.currentTimeMillis() + "_" + originalFilename;
        String objectName = uploadDir + "/" + fileName;

        // 设置文件的访问权限为私有
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());
        metadata.setObjectAcl(CannedAccessControlList.Private);  // 设置访问权限

        InputStream inputStream = file.getInputStream();
        ossClient.putObject(ossBucket, objectName, inputStream, metadata);
        inputStream.close();

        // 生成永不过期的 URL
//        Date expiration = new Date(System.currentTimeMillis() + 10 * 365 * 24 * 60 * 60 * 1000); // 设置 URL 过期时间为 10 年
        Date expiration = new Date(2027584449000L);
        GeneratePresignedUrlRequest generatePresignedUrlRequest =
                new GeneratePresignedUrlRequest(ossBucket, objectName, HttpMethod.GET);
        generatePresignedUrlRequest.setExpiration(expiration);

        URL signedUrl = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        System.out.println(signedUrl.toString());
        return signedUrl.toString(); // 返回已上传文件的带签名的 URL
    }


    // 新方法，用于获取已上传文件的完整URL（包含查询参数）
    public String getUploadedFileUrl(String objectName, String expires, String accessKeyId, String signature) {
        return "https://" + ossBucket + "." + ossEndpoint + "/" + objectName +
                "?Expires=" + expires +
                "&OSSAccessKeyId=" + accessKeyId +
                "&Signature=" + signature;
    }

}
